
import json
import streamlit as st
import pandas as pd
import requests
from translate.languages import languages
from pathlib import Path


def main():

    st.title("东盟语言翻译")

    history_file = 'history.csv'
    if Path(history_file).exists():
        df = pd.read_csv(history_file, index_col=None)
    else:
        df = pd.DataFrame({
            '输入文本': [],
            '源语言': [],
            '目标语言': [],
            '文本标签': [],
            '翻译文本': []
        })
    # 显示20条历史记录
    st.markdown("**历史记录**")
    st.write(df)

    st.markdown("**文本翻译**")
    col1, col2= st.columns(2)
    with col1:
        src_lan = st.selectbox(
            "from",
            ("中文", "英语", "泰语", "越南语", "马来语", "老挝语", "缅甸语", "菲律宾语", "柬埔寨语", "印尼语"),
            index=1,  # 默认选中第一个选项
            help="待翻译文本的语言"
        )
        from_lan = languages[src_lan]

    with col2:
        des_lan = st.selectbox(
            "to",
            ("中文", "英语", "泰语", "越南语", "马来语", "老挝语", "缅甸语", "菲律宾语", "柬埔寨语", "印尼语"),
            index=3,  # 默认选中第3个选项
            help="文本的目标语言"
        )
        to_lan = languages[des_lan]

    input_text = st.text_area('请输入东盟文本', max_chars=500, help='最大长度为500字符')

    clicked = st.button("翻译")
    if clicked:
        try:
            # url = 'https://u359243-9b43-5b4d107f.westx.seetacloud.com:8443/translate'
            # url = 'https://u359243-b31a-04ccc46d.westx.seetacloud.com:8443/translate'
            url = 'https://u359243-9067-9647ad91.westx.seetacloud.com:8443/translate'
            req = requests.post(
                url,
                data=json.dumps({
                    'input_text': input_text,
                    'from_lan': from_lan,
                    'to_lan': to_lan
                })
            )
            result = req.json()['data']
            if result is None:
                return
        except:
            return

        st.markdown(f"**文本标签**：{result['类别标签']}")
        st.markdown(f"**译文**：{result['译文']}")

        df.loc[len(df)] = [input_text, src_lan, des_lan, result['类别标签'], result['译文']]
        if df.shape[0] > 20:
            df.drop(0, axis=0, inplace=True)
        df.to_csv(history_file, index=False)




if __name__ == "__main__":
    main()